package org.jeecg.modules.product.risk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.product.risk.entity.TbBaseMeasuresTaskRecord;
import org.jeecg.modules.product.risk.mapper.TbBaseMeasuresTaskRecordMapper;
import org.jeecg.modules.product.risk.service.ITbBaseMeasuresTaskRecordService;
import org.jeecg.modules.product.until.BaseRiskCommonConstant;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 风险排查记录
 * @Author: jeecg-boot
 * @Date:   2024-04-29
 * @Version: V1.0
 */
@Slf4j
@Service
public class TbBaseMeasuresTaskRecordServiceImpl extends ServiceImpl<TbBaseMeasuresTaskRecordMapper, TbBaseMeasuresTaskRecord> implements ITbBaseMeasuresTaskRecordService, Job {
    @Autowired
    private TbBaseMeasuresTaskRecordMapper baseMeasuresTaskRecordMapper;


    @Override
    public List<Map> countForThisWeekTaskRecordByUsername(String username) {
        return baseMeasuresTaskRecordMapper.countForThisWeekTaskRecordByUsername(username);
    }

    @Override
    public List<TbBaseMeasuresTaskRecord> countForTimeFrame(String nodeType) {
        return baseMeasuresTaskRecordMapper.countForTimeFrame(nodeType);
    }

    @Override
    public Page<TbBaseMeasuresTaskRecord> queryPageListBylistCompositeCondition(Page<TbBaseMeasuresTaskRecord> page, String checkStatus, String nodeType) {
        return page.setRecords(baseMeasuresTaskRecordMapper.queryPageListBylistCompositeCondition(page, checkStatus, nodeType));
    }

    @Override
    public List<Map> countForThisMonthTaskRecord() {
        return baseMeasuresTaskRecordMapper.countForThisMonthTaskRecord();
    }

    @Override
    public List<Map> countByRiskDeviceAndCheckStatus(String startDate, String endDate, String riskDeviceId) {
        return baseMeasuresTaskRecordMapper.countByRiskDeviceAndCheckStatus(startDate, endDate, riskDeviceId);
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("------------------定时任务开始执行---计算风险任务剩余时间---------------");
        QueryWrapper<TbBaseMeasuresTaskRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", CommonConstant.DEL_FLAG_0);
        queryWrapper.eq("check_status", BaseRiskCommonConstant.CHECK_STATUS_NO_INVESTIGATED);
        List<TbBaseMeasuresTaskRecord> recordList = baseMeasuresTaskRecordMapper.selectList(queryWrapper);
        if (!recordList.isEmpty()){
            int count = 0;
            // 获取当前时间
            Date currDate = new Date();
            LocalDateTime now = LocalDateTime.now();
            for (TbBaseMeasuresTaskRecord record : recordList){
                if(record.getTaskEndTime().compareTo(currDate) <= 0){
                    record.setCheckStatus(BaseRiskCommonConstant.CHECK_STATUS_TIME_OUR);
                }else {
                    record.setTimeRemaining(timeRemainingCalculator(now,record.getTaskEndTime(),record.getPeriodUnit()));
                }
                baseMeasuresTaskRecordMapper.updateById(record);
                count++;
            }
            log.info("------------------定时任务执行结束-----计算风险任务剩余时间-供处理数据条数---------"+count);
        }
    }

    /**
     * 计算剩余时间
     * @param now
     * @param taskEndTime
     * @return
     */
    public String timeRemainingCalculator(LocalDateTime now, Date taskEndTime, String periodUnit){
        // 创建一个LocalDateTime实例
        Calendar calender = Calendar.getInstance();
        calender.setTime(taskEndTime);
        LocalDateTime deadline = LocalDateTime.of(calender.get(Calendar.YEAR), calender.get(Calendar.MONTH)+1, calender.get(Calendar.DAY_OF_MONTH), calender.get(Calendar.HOUR_OF_DAY), 0);
        //log.info("---Year----"+calender.get(Calendar.YEAR)+"----Month-----"+calender.get(Calendar.MONTH)+1+"----Day---------"+calender.get(Calendar.DAY_OF_MONTH)+"----Hour---------"+calender.get(Calendar.HOUR_OF_DAY));

        // 计算剩余时间
        Duration duration = Duration.between(now, deadline);
        // 输出剩余时间
        long days = duration.toDays();
        long hours = duration.toHours() % 24;
        long minutes = duration.toMinutes() % 60;
        //long seconds = duration.getSeconds() % 60;
        if(periodUnit.equals("periodType04") || periodUnit.equals("periodType02") || periodUnit.equals("periodType03")){
            return days + "天" + hours + "小时" + minutes + "分钟";
        } else {
            return minutes + "分钟";
        }
    }
}
